from PyQt4.QtGui import QTextEdit
from PyQt4.QtGui import QTextDocument
from PyQt4.QtGui import QTextCursor
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QRegExp

from html_highlighter import HtmlHighlighter

class Editor(QTextEdit):

    def __init__(self, web):
        QTextEdit.__init__(self)
        self._web = web
        self.highlighter = HtmlHighlighter(self)
        self.clipboard = QApplication.clipboard()
        self.autocomplete = True
        self.newDocument = True
        self.path = ''
        #self.connect(self, QtCore.SIGNAL("textChanged()"), self.prueba)

    def prueba(self):
        pass
        #para intellisense
        """self.menu = QtGui.QMenu('Menu')
        self.menu.addAction('Online')
        self.menu.addAction('Busy')
        self.menu.addAction('Away')
        self.menu.addAction('Idle')
        self.menu.addAction('Offline')
        self.menu.popup(QtGui.QCursor.pos())"""

    def keyReleaseEvent(self, e):
        self._web.setHtml(self.toPlainText())
        if self.autocomplete:
            cursorActual = self.textCursor()
            if e.key() == 62:
                self.autocomplete = False
                cursor = self.document().find(QRegExp('<(\w)+'), self.textCursor(), QTextDocument.FindBackward)
                cursor.setPosition(cursor.position())
                self.setTextCursor(cursor)
                self.moveCursor(QTextCursor.PreviousWord, QTextCursor.KeepAnchor)
                self.copy()
                tag = self.clipboard.text()
                self.setTextCursor(cursorActual)
                self.insertPlainText('</' + tag + '>')
                self.moveCursor(QTextCursor.PreviousWord, QTextCursor.MoveAnchor)
                self.moveCursor(QTextCursor.WordLeft, QTextCursor.MoveAnchor)
                self.moveCursor(QTextCursor.Left, QTextCursor.MoveAnchor)
                self.moveCursor(QTextCursor.Left, QTextCursor.MoveAnchor)
                self.autocomplete = True
